package com.msb.controller;

import com.msb.constant.TokenConstant;
import com.msb.params.LoginParams;
import com.msb.params.RegisterParams;
import com.msb.result.RegisterResult;
import com.msb.result.Result;
import com.msb.service.impl.TokenServiceImpl;
import com.msb.utils.UUid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginController
 * @Author: zw
 * @Description: 出百万拳，行万里路；
 * @Create 2024/8/4-07:11
 * @Version 1.0
 */
@RestController
@RequestMapping("token")
public class LoginController {
    @Autowired
    private TokenServiceImpl tokenService;
    @PostMapping("/register")
    public Result register(@RequestBody RegisterParams params, HttpServletResponse response)
    {

        //
        Result result = tokenService.register(params);
        if(!ObjectUtils.isEmpty(result.getData())) {
            RegisterResult registerResult = new RegisterResult();
            UUid uuid = new UUid();
            String uuidValue = uuid.createUUid();
            registerResult.setTicket(uuidValue);
            // 注册成功时应该将cookie 的值设置为令牌值 并且返回到前端响应头
            Cookie cookie = new Cookie("ticket", result.getData().toString());
            // cookie 的有效时间
            cookie.setMaxAge(TokenConstant.EXPIRED_TIME);
            cookie.setPath("/");
            response.addCookie(cookie);
            return Result.ok();
        }
        //

        return result;
    }
    @PostMapping("/login")
    public Result login(@RequestParam LoginParams params, HttpServletResponse response) {
        Result result = tokenService.login(params);
        if(!ObjectUtils.isEmpty(result.getData())) {
            RegisterResult registerResult = new RegisterResult();
            UUid uuid = new UUid();
            String uuidValue = uuid.createUUid();
            registerResult.setTicket(uuidValue);
            // 注册成功时应该将cookie 的值设置为令牌值 并且返回到前端响应头
            Cookie cookie = new Cookie("ticket", result.getData().toString());
            // cookie 的有效时间
            cookie.setMaxAge(TokenConstant.EXPIRED_TIME);
            cookie.setPath("/");
            response.addCookie(cookie);
            return Result.ok();
        }
        //

        return result;
    }
    @PostMapping("/loginOut")
    public Result loginOut(){
        return null;
    }
}
